package com.yoooya.base.commons;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

/**
 * 工具类
 * 
 * @author Sun Yijing<br />
 *         Copyright © Xiamen Yoooya NetWorks Co.,Ltd.
 * @since yoooya software platform v1.0.0
 * @version 1.0.0 <br />
 *          <table border="1" cellpadding="3" cellspacing="0">
 *          <tr>
 *          <th align="left" colspan="3"><b>修改历史</b></th>
 *          </tr>
 *          <tr>
 *          <td>修改日期</td>
 *          <td>修改人</td>
 *          <td>修改描述</td>
 *          </tr>
 *          <tr>
 *          <td>2018-6-20</td>
 *          <td>Sun Yijing</td>
 *          <td>新建</td>
 *          </tr>
 *          </table>
 */
public abstract class CommonUtils {

	/**
	 * 地球半径，单位：米
	 */
	private static final double EARTH_RADIUS = 6378137;
	public static final String HTTP_HOST = "http://";
	public static final String HTTPS_HOST = "https://";
	public static final String SERVICE_DOMAIN = ".qzdishi.cn/";
	/**
	 * 初始化密码
	 */
	public static final String INIT_PASSWORD = "2018yykj2018";

	public static final String SMS_TEMPLATE_ID = "295355";

	/**
	 * <code>AUTH_CODE</code>-验证码标识键。
	 */
	public static final String AUTH_CODE = "auth-code";

	public static final String IMAGE_URL = "/images/";

	public static final Integer PRODUCT_STOCK = 6;

	public static final String PRODUCT_PRICE = "product_price";
	public static final String DONATION_SN = "donation_sn";
	public static final String POSTAGE_SN = "postage_sn";
	public static final int DONATION_LENGTH = 9;
	public static final String DONATION_PREFIX = "SSCY";
	public static final String POSTAGE_PREFIX = "SSCY";
	public static final int DONAION_INTERVAL_TIME = -6;
	public static final String ORDER_MIN_QUANTITY = "order_min_quantity";
	public static final String ORDER_MAX_QUANTITY = "order_max_quantity";
	private static long orderNum = 0l;

	/**
	 * 弧度
	 */
	private static double rad(double d) {
		return d * Math.PI / 180.0;
	}

	/**
	 * 根据两点间经纬度坐标（double值），计算两点间距离，单位为米
	 */
	public static long getDistance(double lng1, double lat1, double lng2,
			double lat2) {
		double radLat1 = rad(lat1);
		double radLat2 = rad(lat2);
		double a = radLat1 - radLat2;
		double b = rad(lng1) - rad(lng2);
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
				+ Math.cos(radLat1) * Math.cos(radLat2)
				* Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return (long) s;
	}

	/**
	 * 字段分割成long类型list
	 * 
	 * @param str
	 *            字符串
	 * @param split
	 *            分割符,未传按","进行分割
	 * @return
	 */
	public static List<Long> string2Long(String str, String split) {
		List<Long> idList = new ArrayList<Long>();
		if (split == null || split.equals("")) {
			split = ",";
		}
		if (str != null && !("".equals(str))) {
			String id[] = str.split(split);
			for (String s : id) {
				idList.add(Long.parseLong(s));
			}
		}
		return idList;
	}

	/**
	 * 字段分割成Integer类型list
	 * 
	 * @param str
	 *            字符串
	 * @param split
	 *            分割符,未传按","进行分割
	 * @return
	 */
	public static List<Integer> string2Integer(String str, String split) {
		List<Integer> idList = new ArrayList<Integer>();
		if (split == null || split.equals("")) {
			split = ",";
		}
		if (str != null && !("".equals(str))) {
			String id[] = str.split(split);
			for (String s : id) {
				idList.add(Integer.parseInt(s));
			}
		}
		return idList;
	}

	public static List<String> string2String(String str, String split) {
		if (StringUtils.isBlank(str)) {
			return null;
		}
		List<String> idList = new ArrayList<String>();
		if (split == null || split.equals("")) {
			split = ",";
		}
		if (str != null && !("".equals(str))) {
			String id[] = str.split(split);
			for (String s : id) {
				idList.add(s);
			}
		}
		return idList;
	}

	public static String md5(String s) {
		return replaceBars(UUID.nameUUIDFromBytes(
				s.getBytes(StandardCharsets.ISO_8859_1)).toString());
	}

	public static String replaceBars(String s) {
		if (StringUtils.contains(s, "-")) {
			return StringUtils.replace(s, "-", "");
		}
		return s;
	}

	public static boolean isNull(Object obj) {
		return null == obj;
	}

	public static boolean isNotNull(Object obj) {
		return !isNull(obj);
	}

	/**
	 * 判断是否为相对路径
	 * 
	 * @param path
	 * @return
	 */
	public static boolean isRelativePath(String path) {
		if (StringUtils.isNotBlank(path)
				&& (path.contains(HTTP_HOST) || path.contains(HTTPS_HOST))) {
			return false;
		}
		return true;
	}

	public static boolean isURL(String str) {
		// 转换为小写
		str = str.toLowerCase();
		String regex = "^((https|http|ftp|rtsp|mms)?://)"
				+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" // ftp的user@
				+ "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
				+ "|" // 允许IP和DOMAIN（域名）
				+ "([0-9a-z_!~*'()-]+\\.)*" // 域名- www.
				+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名
				+ "[a-z]{2,6})" // first level domain- .com or .museum
				+ "(:[0-9]{1,4})?" // 端口- :80
				+ "((/?)|" // a slash isn't required if there is no file name
				+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
		Pattern pattern = Pattern.compile(regex);
		return pattern.matcher(str).matches();

	}

	/**
	 *
	 * @param c
	 *            要填充的字符
	 * @param length
	 *            填充后字符串的总长度
	 * @param prefix
	 *            前缀
	 * @param number
	 *            要格式化的字符串 格式化字符串，左对齐
	 * @return
	 */
	public static String snFormat(char c, int length, String prefix,
			String number) {
		String str = "";
		String cs = "";
		if (number.length() > length) {
			str = number;
		} else {
			for (int i = 0; i < length - number.length(); i++) {
				cs = cs + c;
			}
		}
		str = prefix + cs + number;
		return str;
	}

	public static String listToString(List<Long> list, String separator) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			if (i == list.size() - 1) {
				sb.append(list.get(i));
			} else {
				sb.append(list.get(i));
				sb.append(separator);
			}
		}
		return sb.toString();
	}

	public static String listToString(Integer[] list, String separator) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.length; i++) {
			if (i == list.length - 1) {
				sb.append(list[i]);
			} else {
				sb.append(list[i]);
				sb.append(separator);
			}
		}
		return sb.toString();
	}

	/**
	 * 生成订单编号
	 * 
	 * @return
	 */
	public static synchronized String getOrderNo() {
		String str = new SimpleDateFormat("yyMMddHHmmsss").format(new Date());
		str += String.valueOf(getRandom(100));
		// if (date == null || !date.equals(str)) {
		// date = str;
		// orderNum = 0l;
		// }
		if (orderNum > 999) {
			orderNum = 0l;
		}
		orderNum++;
		long orderNo = Long.parseLong((str)) * 100;
		orderNo += orderNum;
		return orderNo + "";
	}

	public static int getRandom(int r) {
		Random random = new Random();
		int result = random.nextInt(r);
		return result + 1;
	}

	public static void main(String[] args) {
		for (int i = 0; i < 100; i++) {
			System.out.println(getOrderNo());
		}
	}

	/**
	 * 交集
	 * @param list1
	 * @param list2
	 * @return
	 */
	public static List<String> intersectList(List<String> list1,List<String> list2){
		List<String> resultList = new ArrayList<String>();
		for (int i = 0; i < list1.size(); i++) {
			String str1 = list1.get(i);
			for (int j = 0; j < list2.size(); j++) {
				String str2 = list2.get(j);
				if(str1.equals(str2)){
					resultList.add(str1);
					break;
				}
			}
			list2.remove(str1);
		}
		return resultList;
	}

}
